<template>
  <!-- 组合模板 -->
  <el-dialog
    width="1100px"
    title="组合模板"
    destroy-on-close
    append-to-body
    center
    :visible.sync="show"
    :before-close="cancel"
  >
    <div style="margin: 10px 0">
      组合名称: <span style="font-weight: bold">{{ formData.combinationName }}</span>
    </div>
    <div>
      <el-select
        @change="setTemplateInfo"
        style="margin-right: 5px"
        size="mini"
        v-model="selectedTemplate"
        :placeholder="$t('请选择')"
      >
        <el-option v-for="item in templateList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button
        size="mini"
        v-hasPermi="['distribution:skuTempProxy:addCom']"
        type="primary"
        @click="handleAddTemplate"
        v-show="!disabled"
      >
        {{ $t('新增模板') }}
      </el-button>
    </div>
    <el-form
      v-if="type"
      ref="formRef"
      :disabled="disabled"
      :model="form"
      :rules="rules"
      size="mini"
      label-width="90px"
      style="margin-top: 10px"
    >
      <el-row :gutter="10">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" size="mini"></el-input>
        </el-form-item>
        <!-- <el-col :span="10">
      
        </el-col> -->
        <!-- <el-col :span="7">
          <el-form-item label="平台sku" prop="combinationSku">
            <el-input v-model="form.combinationSku" size="mini"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="价格(JPY)" prop="price">
            <el-input
              size="mini"
              v-model="form.price"
              oninput="value=value.replace(/[^\d.]/g, '')"
              controls-position="right"
              :min="0" />
          </el-form-item>
        </el-col> -->
      </el-row>

      <el-form-item :label="$t('标题')" prop="title">
        <el-input v-model="form.title" size="mini" show-word-limit />
      </el-form-item>
      <el-row :gutter="20" style="margin-top: 15px">
        <el-col :span="10" style="padding-left: 0; padding-right: 0; border: 1px solid #eee">
          <!-- 五点描述 -->
          <div class="des-title">五点描述</div>
          <el-descriptions :column="1" border class="des-desc5">
            <el-descriptions-item label="描述1" label-class-name="my-label5" content-class-name="my-content">
              <el-form-item label-width="0" prop="desc1">
                <el-input v-model="form.desc1" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="描述2" label-class-name="my-label5" content-class-name="my-content">
              <el-form-item label-width="0" prop="desc2">
                <el-input v-model="form.desc2" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="描述3" label-class-name="my-label5" content-class-name="my-content">
              <el-form-item label-width="0" prop="desc3">
                <el-input v-model="form.desc3" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="描述4" label-class-name="my-label5" content-class-name="my-content">
              <el-form-item label-width="0" prop="desc4">
                <el-input v-model="form.desc4" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="描述5" label-class-name="my-label5" content-class-name="my-content">
              <el-form-item label-width="0" prop="desc5">
                <el-input v-model="form.desc5" />
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="10">
          <!-- 详细描述 -->
          <div class="des-title" style="border: 1px solid #eee; border-bottom: none">详细描述</div>
          <div class="des-detail">
            <div class="des-detail_left">详情</div>
            <div class="des-detail_right">
              <el-form-item label-width="0" prop="descDetails">
                <el-input
                  style="height: 100%"
                  type="textarea"
                  placeholder="请输入内容"
                  v-model="form.descDetails"
                  :rows="12"
                />
              </el-form-item>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div>
            <!-- 已完成的模板也允许修改 -->
            <el-button
              v-hasPermi="['distribution:skuTempProxy:editCom']"
              type="primary"
              size="small"
              style="margin: 5px 0"
              @click="handleEdit"
              v-show="!disabled && type != 'add' && selectedTemplate"
            >
              修改模板
            </el-button>
            <div v-show="type != 'add'">
              <el-button
                type="danger"
                @click="deleteTemplate"
                size="small"
                v-hasPermi="['distribution:skuTempProxy:deleteCom']"
                v-show="selectedTemplate && form.isComplete != 1"
              >
                删除模板
              </el-button>
            </div>
            <div v-show="type == 'add'">
              <el-button
                size="small"
                v-hasPermi="['distribution:skuTempProxy:addCom']"
                type="success"
                @click="addTemplate"
              >
                确认新增
              </el-button>
            </div>
            <div>
              <div>创建人:{{ form.createByName }}</div>
              <div>创建时间:{{ form.createTime }}</div>
              <div>更新人:{{ form.updateByName }}</div>
              <div>更新时间:{{ form.updateTime }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
      <div v-show="type == 'edit' || type == ''">
        <div style="padding: 10px 0; border-bottom: 1px solid #e1dddd">模板图片</div>
        <el-row>
          <div class="template-img" :style="disabled ? 'pointer-events: none;' : ''">
            <ImgUploadManage
              type="10"
              :businessId="form.id"
              :uploadLimit="10"
              :limit="10"
              :fileList.sync="tempProxyImgList"
            />
          </div>
          <div class="template-img-btns">
            <el-button size="small" @click="handleSaveImg" v-hasPermi="['distribution:skuTempProxy:updateImg']">
              保存图片
            </el-button>
            <div>
              <div>创建人:{{ imgInfo.createByName }}</div>
              <div>创建时间:{{ imgInfo.createTime }}</div>
              <div>更新人:{{ imgInfo.updateByName }}</div>
              <div>更新时间:{{ imgInfo.updateTime }}</div>
            </div>
          </div>
        </el-row>
      </div>
    </el-form>
    <div style="text-align: right; margin-top: 30px">
      <el-button disabled v-if="form.isComplete == 1"> 已完成 </el-button>

      <!-- isComplete==1 已完成模板 -->
      <el-button
        v-show="form.isComplete != 1 && type !== 'add' && selectedTemplate"
        v-hasPermi="['distribution:skuTempProxy:completeTempCom']"
        @click="handleCompleteTemp"
      >
        完成模板
      </el-button>
      <el-button @click="cancel">{{ $t('关闭') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getSkuProxyTemplateListCom,
  addCom,
  editCom,
  deleteCom,
  completeTempCom,
  acceptanceTempCom,
  updateImg,
} from '@/api/distribution/sku/skuTempProxyApply'
import draggable from 'vuedraggable'

export default {
  components: { draggable },

  props: {
    /**组合id */
    combinationId: {
      type: String,
    },
    /**
     * formData
     */
    formData: {
      type: Object,
      default: {},
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      tempProxyImgList: '',
      waitUploadList: [],
      uploadFlag: false,
      type: '',
      /**当前选择模板id */
      selectedTemplate: '',
      /**模板列表 */
      templateList: [],
      imgInfo: {
        createByName: '',
        createTime: '',
        updateByName: '',
        updateTime: '',
      },
      form: {
        /**完成状态 */
        isComplete: '',
        id: '',
        combinationId: '',
        /**平台sku */
        combinationSku: '',
        /**模板名称 */
        name: '',
        distrId: '',
        /**价格(JPY) */
        price: '',
        /**标题 */
        title: '',
        /**描述1 */
        desc1: '',
        /**描述2 */
        desc2: '',
        /**描述3 */
        desc3: '',
        /**描述4 */
        desc4: '',
        /**描述5 */
        desc5: '',
        /**详情 */
        descDetails: '',
        /**模板图片 */
        tempProxyImgList: [],
      },
      rules: {
        name: [{ validator: this.validLength, required: true, trigger: 'change' }],
        // combinationSku: [{ required: true, message: '请输入', trigger: 'blur' }],
        // price: [{ required: true, message: '请输入', trigger: 'blur' }],
        title: [{ validator: this.validLength, required: true, trigger: 'change' }],
        desc1: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc2: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc3: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc4: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc5: [{ validator: this.validLength, required: false, trigger: 'change' }],
        descDetails: [{ validator: this.validLength, required: false, trigger: 'change' }],
      },
    }
  },
  computed: {},
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.resetForm()
        this.getList()
      }
    },
  },
  methods: {
    handleSaveImg() {
      const data = {
        tempId: this.selectedTemplate,
        imgUrlList: this.tempProxyImgList?.split(',')?.map((i, index) => {
          return {
            imgUrl: i,
            sort: index + 1,
          }
        }),
      }
      updateImg(data).then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.$message({ type: 'success', message: msg })
          this.getList()
        }
      })
    },
    handleAcceptanceTemp() {
      const message = this.$t('请确定全部完成后验收，验收完成时会将文案代做的模板追加到该sku的模板上')
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        acceptanceTempCom(this.formData.id).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })
            this.cancel()
            this.$emit('getList')
          }
        })
      })
    },
    handleCompleteTemp() {
      this.$confirm('确定完成模板?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        completeTempCom(this.selectedTemplate).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })
            this.cancel()
            this.$emit('getList')
          }
        })
      })
    },
    /**验证长度 */
    validLength(rule, value, callback) {
      const { field } = rule
      const strLength = value.length

      // name
      if (field == 'name') {
        if (!value) {
          return callback(new Error(`请输入`))
        }
        //  长度最大为 20
        if (strLength > 20) {
          return callback(new Error(`文字超长 ${strLength} / 20`))
        }
      }
      // descDetails
      if (field == 'descDetails') {
        //  长度最大为 3000
        if (strLength > 3000) {
          return callback(new Error(`文字超长 ${strLength} / 3000`))
        }
      }

      // title
      if (field == 'title') {
        if (!value) {
          return callback(new Error(`请输入`))
        }
        //  长度最大为 300
        if (strLength > 300) {
          return callback(new Error(`文字超长 ${strLength} / 300`))
        }
      }

      // 五点描述 长度最大为 500
      if (field == 'desc1' || field == 'desc2' || field == 'desc3' || field == 'desc4' || field == 'desc5') {
        // 五点描述 长度最大为 500
        if (strLength > 500) {
          return callback(new Error(`文字超长 ${strLength} / 500`))
        }
      }
      return callback()
    },

    deleteTemplate() {
      this.$confirm(this.$t('确认删除?'), this.$t('提示'), {
        type: 'warning',
      }).then(() => {
        deleteCom(this.selectedTemplate).then((res) => {
          const { code, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })
            this.resetForm()
            this.getList()
          }
        })
      })
    },
    setTemplateInfo(id) {
      this.resetForm()
      const info = this.templateList.filter((item) => item.id == id || item.name == id)[0] || {}
      this.selectedTemplate = info.id
      Object.keys(this.form).forEach((key) => {
        const _data = JSON.parse(JSON.stringify(info))
        if (key == 'tempProxyImgList') {
          this.tempProxyImgList = (_data[key] || [])?.map((i) => i.templateImgUrl)?.toString()
          this.form[key] = _data[key] ? _data[key] : []
        } else {
          this.form[key] = _data[key] ? _data[key] : ''
        }
      })
      // this.type = ''
      this.type = 'edit'
    },
    setImgInfo(data) {
      if (data) {
        this.imgInfo = {
          createByName: data.createByName,
          createTime: data.createTime,
          updateByName: data.updateByName,
          updateTime: data.updateTime,
        }
      }
    },
    getList(templateName = null) {
      getSkuProxyTemplateListCom({ id: this.formData.id }).then((res) => {
        const { tempProxyList } = res.data
        this.setImgInfo(tempProxyList[0])
        this.templateList = tempProxyList
        /***************************设置相关信息******************************/
        if (templateName) {
          this.setTemplateInfo(templateName)
        } else {
          this.setTemplateInfo(this.templateList[0]?.id)
        }
        /***************************设置相关信息******************************/

        if (this.templateList.length == 0) {
          this.type = ''
        }
      })
    },
    handleAddTemplate() {
      if (this.formData.num <= this.templateList.length) {
        this.$message({ type: 'error', message: '模板数量不能超过申请数量' })
        return
      }
      this.type = 'add'
      this.selectedTemplate = ''
      this.resetForm()
      this.form.combinationId = this.formData.combinationId
    },
    addTemplate() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = JSON.parse(
            JSON.stringify({
              ...this.form,
              applyId: this.formData.id,
            }),
          )
          addCom(data).then((res) => {
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              const templateName = JSON.parse(JSON.stringify(this.form.name))
              this.getList(templateName)
              this.type = ''
            }
          })
        }
      })
    },
    handleEdit() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify({ ...this.form, applyId: this.formData.id }))
          editCom(data).then((res) => {
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              const templateName = JSON.parse(JSON.stringify(this.form.name))
              this.getList(templateName)
              this.type = ''
            }
          })
        }
      })
    },

    resetForm() {
      Object.keys(this.form).forEach((key) => (this.form[key] = ''))
      this.form.tempProxyImgList = []
      this.tempProxyImgList = ''
    },

    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>

<style lang="scss" scoped>
.el-form-item {
  // margin-bottom: 5px;
}

.my-label5 {
  text-align: center !important;
}

.des-title {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
.des-desc5 {
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
}

.des-detail {
  display: flex;
  height: 265px;

  &_left {
    width: 40%;
    display: flex;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #e1dddd;
  }

  &_right {
    padding: 10px;
    flex: 1;

    ::v-deep textarea {
      height: 100%;
    }
  }
}

.el-form-item {
  // margin-bottom: 5px;
}

.my-label5 {
  text-align: center !important;
}

.des-detail {
  display: flex;
  height: 265px;
  border: 1px solid #e1dddd;

  &_left {
    width: 40%;
    display: flex;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #e1dddd;
  }

  &_right {
    padding: 10px;
    flex: 1;

    ::v-deep textarea {
      height: 100%;
    }
  }
}

.template-img {
  display: flex;
  overflow: auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  &-list {
    width: calc(100% - 200px);
    display: flex;
    overflow: auto;
  }
  &-btns {
    width: 200px;
    padding-left: 5px;
    display: flex;
    flex-direction: column;
  }
}
</style>
